﻿using System;
using System.Collections.Generic;
using System.Reflection;
using MedicService.Domain.Generic;
using MedicService.Domain.Print.Template;
using MedicService.Server.Factory;

namespace MedicService.Domain.Print {
    public class PrintOrder : PrintEntity {
        private PrintOrder() { }

        public PrintOrder(PrintTemplate<PrintOrder> template, Order order) {
            Init(template);
            order = new OrderFactory().Load(order.Id);
            Replace(template, order);

            int index = 0;

            do {
                int start = this.Html.IndexOf("[Doctor]", index);
                int end = this.Html.IndexOf("[/Doctor]", index) + 9;
                index = end;

                if (start >= 0 && end >= 0 && end >= start) {
                    string s = this.Html.Substring(start, end - start);
                    string doctors = s.Replace("[Doctor]", "").Replace("[/Doctor]", "");
                    string replace = "";
                    List<Doctor> doctorList = new DoctorFactory(true).GetListByOrder(order);
                    string lastG = null;
                    foreach (var doctor in doctorList) {
                        string s1 = Replace(doctors, doctor);
                        int startG = s1.IndexOf("[Group]");
                        int endG = s1.IndexOf("[/Group]") + 8;
                        string g = null;
                        if (startG >= 0) {
                            g = s1.Substring(startG, endG - startG);
                            if (!string.IsNullOrEmpty(g) && g.Equals(lastG)) {
                                s1 = s1.Replace(g, "");
                            } else {
                                s1 = s1.Replace(g, g.Replace("[Group]", "").Replace("[/Group]", ""));
                            }
                        }
                        replace += s1;
                        lastG = g;
                    }
                    this.Html = this.Html.Replace(s, replace);
                }
            } while (index > 8);
        }

    }
}